package com.micangcaihang.micang.mvp.task.ui;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.micangcaihang.common.base.fragment.BaseListFragment;
import com.micangcaihang.common.utils.BeanUtils;
import com.micangcaihang.common.utils.ConvertUtils;
import com.micangcaihang.common.utils.StringUtils;
import com.micangcaihang.common.utils.TimeUtils;
import com.micangcaihang.common.utils.ToastUtils;
import com.micangcaihang.micang.R;
import com.micangcaihang.micang.adapter.FTaskCommonOwnerInfoAdapter;
import com.micangcaihang.micang.databinding.FragmentTaskCommonOwnerInfoFBinding;
import com.micangcaihang.micang.entity.FTaskCommonOwnerInfoEntity;
import com.micangcaihang.micang.entity.MatesEntity;
import com.micangcaihang.micang.entity.PickerEntity;
import com.micangcaihang.micang.mvp.task.contract.FTaskCommonOwnerInfoContract;
import com.micangcaihang.micang.mvp.task.presenter.FTaskCommonOwnerInfoPresenter;
import com.micangcaihang.micang.util.DialogHelper;
import com.micangcaihang.micang.view.PickerViewHelper;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * <pre>
 *     author : Fandy
 *     e-mail : fandayongfly@gmail.com
 *     time   : 2017/07/24
 *     update : 2017/07/24
 *     desc   : 风控 共有人信息
 *     version: 1.0
 * </pre>
 */

public class FTaskCommonOwnerInfoFragment extends BaseListFragment<FTaskCommonOwnerInfoPresenter,
        FTaskCommonOwnerInfoAdapter, FragmentTaskCommonOwnerInfoFBinding> implements FTaskCommonOwnerInfoContract.View {
    private String id;
    private int mCurrentPos;
    private int mPickerType;
    private List<FTaskCommonOwnerInfoEntity> mOldData;
    private int maxLength = 5;
    private boolean isNetSuccess;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        id = getArguments().getString("id");
    }

    public static FTaskCommonOwnerInfoFragment newInstance(String id) {
        Bundle args = new Bundle();
        FTaskCommonOwnerInfoFragment fragment = new FTaskCommonOwnerInfoFragment();
        args.putString("id", id);
        fragment.setArguments(args);
        return fragment;
    }

    /**
     * 获取资源文件布局
     *
     * @return 资源布局文件layout
     */
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_task_common_owner_info_f;
    }

    @Override
    public void initPresenter() {
        super.initPresenter();
        mPresenter.setId(id);
    }

    /**
     * recycleView的设置
     */
    @Override
    protected void initAdapter() {
        mOldData = new ArrayList<>();
        mAdapter = new FTaskCommonOwnerInfoAdapter(R.layout.item_task_common_owner_info_f, new ArrayList<>());
        mViewBinding.recyclerView.setAdapter(mAdapter);
    }

    /**
     * 初始化各种状态处理
     * 在这个方法里处理的是recyclerview的所有的初始化，
     * 包括对他的展示形式，是list或grid或瀑布流
     */
    @Override
    protected void initRecyclerViewSetting() {

    }

    /**
     * 初始化按钮监听
     */
    @Override
    protected void initListener() {
        mViewBinding.setClickHandler(new ClickHandler());
        mRecyclerView.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                FTaskCommonOwnerInfoEntity entity = mAdapter.getData().get(position);
                mCurrentPos = position;
                switch (view.getId()) {
                    case R.id.lly_item_customer_sex:
                        mPickerType = 1;
                        mPresenter.loadPickerViewData("sex_list", "性别");
                        break;
                    case R.id.lly_item_marriage_status:
                        mPickerType = 2;
                        mPresenter.loadPickerViewData("marriage_status", "婚姻");
                        break;
                    case R.id.lly_item_certificate_type:
                        mPickerType = 3;
                        mPresenter.loadPickerViewData("certificate_type", "证件类型");
                        break;
                    case R.id.lly_item_peason_credit:
                        mPickerType = 4;
                        mPresenter.loadPickerViewData("peason_credit", "征信状况");
                        break;
                    case R.id.lly_item_peason_crediless:
                        mPickerType = 5;
                        mPresenter.loadPickerViewData("li_boolean", "是否失信");
                        break;
                    case R.id.lly_item_peason_enforced:
                        mPresenter.loadPickerViewData("li_boolean", "是否被执行");
                        mPickerType = 6;
                        break;
                    case R.id.lly_item_query_time:
                        Calendar startDate = Calendar.getInstance();
                        startDate.set(1955, 0, 1);
                        Calendar endData = Calendar.getInstance();//系统当前时间
                        Calendar selectData = Calendar.getInstance();
                        if (!StringUtils.isEmpty(entity.getQuery_time())) {
                            selectData.setTime(TimeUtils.millis2Date(Long.parseLong(entity.getQuery_time()) * 1000));
                        }
                        PickerViewHelper.showYearMonthDayPicker(_mActivity, "查询时间(征信)", startDate, endData, selectData, new PickerViewHelper.OnTimeSelectListenner() {
                            @Override
                            public void onTimeSelect(Date date) {
                                String date2String = TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()));
                                String checkin_date = String.valueOf(TimeUtils.string2Millis(date2String, new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())) / 1000);
                                entity.setQuery_time(checkin_date);
                                mAdapter.notifyItemChanged(mCurrentPos);
                            }
                        });
                        break;
                    case R.id.lly_item_relationship_type:
                        mPresenter.loadPickerViewData("relationship_type", "与借款人关系");
                        mPickerType = 7;
                        break;
                    case R.id.btn_delete:
                        DialogHelper.showDeleteUserDialog(_mActivity, "确定删除当前共有人?", () -> {
                            if (StringUtils.isEmpty(entity.getCustomer_id())) {
                                mAdapter.remove(mCurrentPos);
                                mOldData.remove(mCurrentPos);
                            } else {
                                mPresenter.deleteUser(entity.getCustomer_id());
                            }
                        });
                        break;
                }
            }
        });
    }

    /**
     * 返回下拉框信息
     *
     * @param list
     * @param type
     */
    @Override
    public void returnPickerViewData(List<PickerEntity> list, String type) {
        switch (mPickerType) {
            case 1:
                PickerViewHelper.showOnePickerView(_mActivity, type, mAdapter.getData().get(mCurrentPos).getCustomer_sex(), list,
                        pickerEntity1 -> {
                            mAdapter.getData().get(mCurrentPos).setCustomer_sex(pickerEntity1.getSign_id());
                            mAdapter.getData().get(mCurrentPos).getChoose_list().setCustomer_sex(pickerEntity1.getTitle());
                            mAdapter.notifyItemChanged(mCurrentPos);
                        });
                break;
            case 2:
                PickerViewHelper.showOnePickerView(_mActivity, type, mAdapter.getData().get(mCurrentPos).getMarriage_status(), list,
                        pickerEntity1 -> {
                            mAdapter.getData().get(mCurrentPos).setMarriage_status(pickerEntity1.getSign_id());
                            mAdapter.getData().get(mCurrentPos).getChoose_list().setMarriage_status(pickerEntity1.getTitle());
                            List<MatesEntity> mates = mAdapter.getData().get(mCurrentPos).getMates();
                            boolean isHaveNew = false;
                            boolean isHaveOld = false;
                            boolean isHanceWid = false;
                            switch (pickerEntity1.getSign_id()) {
                                case "2":
                                    //循环遍历现任配偶,如果已经有不做任何操作
                                    //如果没有重新new一个添加进去
                                    for (MatesEntity matesEntity : mates) {
                                        if ("1".equals(matesEntity.getRelationship_type())) {
                                            isHaveNew = true;
                                            break;
                                        }
                                    }
                                    if (!isHaveNew) {
                                        MatesEntity Current = new MatesEntity("1");
                                        mates.add(Current);
                                    }
                                    break;
                                case "3":
                                    //循环遍历现任配偶,如果已经有不做任何操作
                                    //如果没有重新new一个添加进去
                                    for (MatesEntity matesEntity : mates) {
                                        if ("1".equals(matesEntity.getRelationship_type())) {
                                            isHaveNew = true;
                                            break;
                                        }
                                    }
                                    if (!isHaveNew) {
                                        MatesEntity Current = new MatesEntity("1");
                                        mates.add(Current);
                                    }
                                    //循环遍历前任配偶,如果已经有不做任何操作
                                    //如果没有重新new一个添加进去
                                    for (MatesEntity matesEntity : mates) {
                                        if ("2".equals(matesEntity.getRelationship_type())) {
                                            isHaveOld = true;
                                            break;
                                        }
                                    }
                                    if (!isHaveOld) {
                                        MatesEntity Current = new MatesEntity("2");
                                        mates.add(Current);
                                    }
                                    break;
                                case "4":
                                    //循环遍历前任配偶,如果已经有不做任何操作
                                    //如果没有重新new一个添加进去
                                    for (MatesEntity matesEntity : mates) {
                                        if ("2".equals(matesEntity.getRelationship_type())) {
                                            isHaveOld = true;
                                            break;
                                        }
                                    }
                                    if (!isHaveOld) {
                                        MatesEntity Current = new MatesEntity("2");
                                        mates.add(Current);
                                    }
                                    break;
                                case "5":
                                    //循环遍历前任配偶,如果已经有不做任何操作
                                    //如果没有重新new一个添加进去
                                    for (MatesEntity matesEntity : mates) {
                                        if ("3".equals(matesEntity.getRelationship_type())) {
                                            isHanceWid = true;
                                            break;
                                        }
                                    }
                                    if (!isHanceWid) {
                                        MatesEntity Current = new MatesEntity("3");
                                        mates.add(Current);
                                    }
                                    break;
                                default:
                                    break;
                            }
                            mAdapter.notifyItemChanged(mCurrentPos);
                        });
                break;
            case 3:
                PickerViewHelper.showOnePickerView(_mActivity, type, mAdapter.getData().get(mCurrentPos).getCertificate_type(), list,
                        pickerEntity1 -> {
                            mAdapter.getData().get(mCurrentPos).setCertificate_type(pickerEntity1.getSign_id());
                            mAdapter.getData().get(mCurrentPos).getChoose_list().setCertificate_type(pickerEntity1.getTitle());
                            mAdapter.notifyItemChanged(mCurrentPos);
                        });
                break;
            case 4:
                PickerViewHelper.showOnePickerView(_mActivity, type, mAdapter.getData().get(mCurrentPos).getPeason_credit(), list,
                        pickerEntity1 -> {
                            mAdapter.getData().get(mCurrentPos).setPeason_credit(pickerEntity1.getSign_id());
                            mAdapter.getData().get(mCurrentPos).getChoose_list().setPeason_credit(pickerEntity1.getTitle());
                            mAdapter.notifyItemChanged(mCurrentPos);
                        });
                break;
            case 5:
                PickerViewHelper.showOnePickerView(_mActivity, type, mAdapter.getData().get(mCurrentPos).getPeason_crediless(), list,
                        pickerEntity1 -> {
                            mAdapter.getData().get(mCurrentPos).setPeason_crediless(pickerEntity1.getSign_id());
                            mAdapter.getData().get(mCurrentPos).getChoose_list().setPeason_crediless(pickerEntity1.getTitle());
                            mAdapter.notifyItemChanged(mCurrentPos);
                        });
                break;
            case 6:
                PickerViewHelper.showOnePickerView(_mActivity, type, mAdapter.getData().get(mCurrentPos).getPeason_enforced(), list,
                        pickerEntity1 -> {
                            mAdapter.getData().get(mCurrentPos).setPeason_enforced(pickerEntity1.getSign_id());
                            mAdapter.getData().get(mCurrentPos).getChoose_list().setPeason_enforced(pickerEntity1.getTitle());
                            mAdapter.notifyItemChanged(mCurrentPos);
                        });
                break;
            case 7:
                PickerViewHelper.showOnePickerView(_mActivity, type, mAdapter.getData().get(mCurrentPos).getRelationship_type(), list,
                        pickerEntity1 -> {
                            mAdapter.getData().get(mCurrentPos).setRelationship_type(pickerEntity1.getSign_id());
                            mAdapter.getData().get(mCurrentPos).getChoose_list().setRelationship_type(pickerEntity1.getTitle());
                            mAdapter.notifyItemChanged(mCurrentPos);
                        });
                break;
        }

    }

    /**
     * 返回共有人信息
     *
     * @param list
     */
    @Override
    public void returnCommonOwnerInfoData(List<FTaskCommonOwnerInfoEntity> list) {
        isNetSuccess = true;
        mOldData.clear();
        try {
            mOldData.addAll(BeanUtils.deepCopy(list));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        mAdapter.setNewData(list);
    }

    /**
     * 保存成功回调
     */
    @Override
    public void onSaveSucceed() {
//        mPresenter.loadCommonOwnerInfoData();
    }

    /**
     * 删除用户成功
     */
    @Override
    public void onDeleteSucceed() {
        mAdapter.remove(mCurrentPos);
        mOldData.remove(mCurrentPos);
    }

    public class ClickHandler {
        public void onAdd(View view) {
            boolean isEmpty = false;
            int index = 0;
            for (FTaskCommonOwnerInfoEntity entity : mAdapter.getData()) {
                if (entity.checkEmpty()) {
                    isEmpty = true;
                }
                index++;
            }
            if (isEmpty) {
                ToastUtils.showLong("请务必填写共有人" + ConvertUtils.StringToNumber(index) + "的姓名,再添加下一个共有人");
            } else if (mAdapter.getData().size() >= maxLength) {
                ToastUtils.showLong("最多添加5个共有人");
            } else {
                FTaskCommonOwnerInfoEntity entity = new FTaskCommonOwnerInfoEntity();
                List<MatesEntity> list = new ArrayList<>();
                MatesEntity matesEntity = new MatesEntity();
                list.add(matesEntity);
                entity.setMates(list);
                mAdapter.addData(entity);

                FTaskCommonOwnerInfoEntity oldEntity = new FTaskCommonOwnerInfoEntity();
                List<MatesEntity> oldList = new ArrayList<>();
                MatesEntity oldmatesEntity = new MatesEntity();
                oldList.add(oldmatesEntity);
                oldEntity.setMates(oldList);
                mOldData.add(oldEntity);
                mRecyclerView.smoothScrollToPosition(mAdapter.getItemCount() - 1);
            }
        }

        public void onSave(View view) {
            saveData();
        }
    }

    /**
     * 开始保存数据请求
     */
    public void saveData() {
        int index = 0;
        boolean isEmpty = false;
        for (FTaskCommonOwnerInfoEntity request : mAdapter.getData()) {
            if (request.checkEmpty()) {
                isEmpty = true;
            }
            index++;
        }
        if (isEmpty) {
            ToastUtils.showLong("请务必填写共有人" + ConvertUtils.StringToNumber(index) + "的姓名,再保存数据");
        } else if (mAdapter.getData().toString().equals(mOldData.toString())) {
            ToastUtils.showLong("您没有更改任何信息，无需保存");
            return;
        } else {
            isNetSuccess = false;
            mPresenter.saveCommonOwnerInfo(mAdapter.getData(), id);
        }
    }

    /**
     * 判断是否保存过数据 没有的话点击保存去保存
     *
     * @return 是否保存当前页面数据
     */
    public boolean isSaveData() {
        //如果请求错误则返回true
        if (!isNetSuccess) {
            return true;
        }
        List<FTaskCommonOwnerInfoEntity> data = mAdapter.getData();
        if (data.toString().equals(mOldData.toString())) {
            return true;
        } else {
            return false;
        }
    }

}
